package net.gz01.wallet.web.controller.admin;

import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;

import net.gz01.wallet.common.PageRespon;
import net.gz01.wallet.common.ZOSearchCondition;
import net.gz01.wallet.web.controller.BaseController;
import net.gz01.wallet.web.model.Dictionary;

public class DictionaryController extends BaseController{

	public void search(){
		render("basedata/dictionary.html");
	}

	public void parentJson() {
		List<Dictionary> items = Dictionary.dao.selectParent();
		renderJson(items);
	}

	public void childrenJson() {
		ZOSearchCondition sc = getSearchCondition();
		List<Dictionary> items = Dictionary.dao.selectChild(sc);
		Page<Dictionary> pageResult = new Page<>(items, 0, items.size(), 1, items.size());
		renderJson(new PageRespon(pageResult));
	}

	public void addPage(){
		String parentCode = getPara("parentCode");
		if(!("0").equals(parentCode)) {
			Dictionary parent = Dictionary.dao.selectByKey(parentCode);
			setAttr("parent", parent);
		}
		setAttr("parentCode", parentCode);
		render("basedata/dictionaryAdd.html");
	}

	public void updatePage(){
		Dictionary dictionary = Dictionary.dao.findById(getPara("id"));
		setAttr("dictionary", dictionary);
		if(!dictionary.getParentCode().equals("0")) {
			setAttr("parent", Dictionary.dao.selectByKey(dictionary.getParentCode()));
		}
		render("basedata/dictionaryUpdate.html");
	}

	public void add(){
		Dictionary dictionary = getModel(Dictionary.class);
		if(StrKit.isBlank(dictionary.getParentCode())) {
			dictionary.setParentCode("0");
		}
		Dictionary temp = Dictionary.dao.selectByKey(dictionary.getCode());
		if(temp != null) {
			renderFail("编码已存在,不允许重复");
		}else {
			dictionary.save();
			renderSuccess();
		}
	}

	public void update(){
		Dictionary dictionary = getModel(Dictionary.class);
		dictionary.update();
		renderSuccess();
	}

	@Before(Tx.class)
	public void delete(){
		Dictionary dictionary = Dictionary.dao.findById(getPara("id"));
		if(dictionary.getParentCode().equals("0")) {
			Dictionary.dao.deleteByParentCode(dictionary.getCode());
		}
		dictionary.delete();
		renderSuccess(false);
	}

	public void autocomplete(){
		String p = getPara("p");
		List<Dictionary> dictionaryList = Dictionary.dao.selectByParentKey(p);

		JSONObject j = new JSONObject();
		j.put("type", "success");
		j.put("code", "0");
		j.put("content", dictionaryList);
		renderJson(j);

	}

}
